package com.yangoxix.lovegoing.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yangoxix.lovegoing.page.ActivityPage;
import com.yangoxix.lovegoing.page.LoginPage;
import com.yangoxix.lovegoing.pojo.User;
import com.yangoxix.lovegoing.service.ActivityService;
import com.yangoxix.lovegoing.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.util.Strings;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
@Api(tags="用户操作接口")
@Controller
@RequestMapping("/user")
public class UserController {
    private final UserService userService;
    private final ActivityService activityService;
    private final ObjectMapper objectMapper;

    public UserController(UserService userService, ActivityService activityService, ObjectMapper objectMapper) {
        this.userService = userService;
        this.activityService = activityService;
        this.objectMapper = objectMapper;
    }

    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestParam("username") String username,
                                           @RequestParam("password") String password,
                                           @RequestParam("email") String email) {
        return userService.register(username, password, email) ? entityOfRegisterSucceed() : entityOfUserExisted();

    }

    private ResponseEntity<String> entityOfRegisterSucceed() {
        return new ResponseEntity<>("注册成功", HttpStatus.OK);
    }

    private ResponseEntity<String> entityOfUserExisted() {
        return new ResponseEntity<>("用户已存在", HttpStatus.OK);
    }




    @RequestMapping("/login")
    @ResponseBody
    public ResponseEntity login(@RequestParam("username") String username,@RequestParam("password") String password) throws Exception {

        if (!userService.isUserExisted(username)) {
            return entityOfUserNotExisted();
        } else {
            Optional<LoginPage> tokenOptional = userService.login(username, password);
            if (tokenOptional.isPresent()) {
                return entityOfLoginToken(tokenOptional.get());
            } else {
                return entityOfIncorrectPassword();
            }
        }
    }

    public ResponseEntity<String> entityOfLoginToken(LoginPage token) throws Exception {
        String tokenAsJson = objectMapper.writeValueAsString(token);
        return new ResponseEntity<>(tokenAsJson, HttpStatus.OK);
    }

    //    根据用户名查询用户
    @GetMapping("findbyname")
    @ResponseBody
    public User find_User_By_Username(@RequestParam("username") String userName) {
        User byUserName = userService.findByUserName(userName);
        return byUserName;
    }

    @ApiOperation("获取参加过的活动")
    @PostMapping("/participated")
    public ResponseEntity<String> activitiesViaUsername(@RequestParam("username") String username) throws Exception {
        if (!userService.isUserExisted(username)) {
            return entityOfUserNotExisted();
        }
        List<ActivityPage> activities = activityService.activityPagesViaUsername(username);
        return entityOfParticipantActivities(activities);
    }

    private ResponseEntity<String> entityOfUserNotExisted() {
        return new ResponseEntity<>("用户不存在", HttpStatus.BAD_REQUEST);
    }

    private ResponseEntity<String> entityOfParticipantActivities(List<ActivityPage> activities) throws Exception {
        String activitiesAsJson = objectMapper.writeValueAsString(activities);
        return new ResponseEntity<>(activitiesAsJson, HttpStatus.OK);
    }

    @ApiOperation("上传格言")
    @GetMapping("/uploadMotto")
    public ResponseEntity<String> updateMotto(@RequestParam("username") String username,
                                              @RequestParam("newMotto") String motto) {
        if (!userService.isUserExisted(username)) {
            return entityOfUserNotExisted();
        } else {
            userService.updateMotto(username, motto);
            return entityOfMottoUpdated();
        }
    }

    private ResponseEntity<String> entityOfMottoUpdated() {
        return new ResponseEntity<>("格言已更新", HttpStatus.OK);
    }

    @ApiOperation("忘记密码")
    @PostMapping("/forget")
    public ResponseEntity<String> tryResetPassword(@RequestParam("email") String email) {
        if (!userService.isUserExistedViaEmail(email)) {
            return entityOfUserNotExisted();
        } else {
            userService.trySendRecoverEmail(email);
            return entityOfRecoverEmailSent();
        }
    }

    private ResponseEntity<String> entityOfRecoverEmailSent() {
        return new ResponseEntity<>("密码找回邮件已发送", HttpStatus.OK);
    }

    @ApiOperation("修改密码")
    @GetMapping("/changePassword")
    public ResponseEntity<String> tryUpdatePassword(@RequestParam("username") String username,
                                                    @RequestParam("oldpassword") String oldPassword,
                                                    @RequestParam("newpassword") String newPassword) {
        if (!userService.isUserExisted(username)) {
            return entityOfUserNotExisted();
        } else {
            boolean ok = userService.tryUpdatePassword(username, oldPassword, newPassword);
            return ok ? entityOfPasswordUpdated() : entityOfIncorrectPassword();
        }
    }

    private ResponseEntity<String> entityOfPasswordUpdated() {
        return new ResponseEntity<>("密码已更新", HttpStatus.OK);
    }

    private ResponseEntity<String> entityOfIncorrectPassword() {
        return new ResponseEntity<>("密码错误", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ApiOperation("获取头像")
    @GetMapping("/portrait")
    public ResponseEntity<String> getPortraitByUsername(@RequestParam("username") String username) {
        if (!userService.isUserExisted(username)) {
            return entityOfUserNotExisted();
        } else {
            Optional<String> portrait = userService.getPortraitByUsername(username);
            if (!portrait.isPresent() || Strings.isBlank(portrait.get())) {
                return entityOfUserPortraitNotExist();
            } else {
                return entityOfUserPortrait(portrait.get());
            }
        }
    }

    private ResponseEntity<String> entityOfUserPortrait(String imgUrl) {
        return new ResponseEntity<>(imgUrl, HttpStatus.OK);
    }

    private ResponseEntity<String> entityOfUserPortraitNotExist() {
        return new ResponseEntity<>("用户无头像", HttpStatus.OK);
    }

    private ResponseEntity<String> entityOfUserMotto(String motto) {
        return new ResponseEntity<>(motto, HttpStatus.OK);
    }

    private ResponseEntity<String> entityOfUnknownError() {
        return new ResponseEntity<>("未知错误", HttpStatus.INTERNAL_SERVER_ERROR);
    }
    @ApiOperation("获取格言")
    @GetMapping("/motto")
    public ResponseEntity<String> getMottoByUsername(@RequestParam("username") String username) {
        if (userService.isUserExisted(username)) {
            Optional<String> mottoByUsername = userService.getMottoByUsername(username);
            return entityOfUserMotto(mottoByUsername.orElse(""));
        } else {
            return entityOfUserNotExisted();
        }
    }
}
